package com.decade.order.service.impl;

import com.decade.order.entity.Order;
import com.decade.order.feign.AccountClient;
import com.decade.order.feign.EasyIdClient;
import com.decade.order.feign.StorageClient;
import com.decade.order.mapper.OrderMapper;
import com.decade.order.service.OrderService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;

/**
 * @Author: decade
 * @Description:
 * @Date: 2021/1/27 13:24
 **/
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AccountClient accountClient;
    @Autowired
    private StorageClient storageClient;
    @Autowired
    private EasyIdClient easyIdClient;

    @GlobalTransactional//开启全局事务
    @Transactional//本地事务
    @Override
    public void create(Order order) {

       String s = easyIdClient.nextId("order_business");
        Long orderId = Long.valueOf(s);
        // TODO: 从全局唯一id发号器获得id，这里暂时随机产生一个 orderId
//        Long orderId = Long.valueOf(new Random().nextInt(Integer.MAX_VALUE));
        order.setId(orderId);

        orderMapper.create(order);

        //  调用storage，修改库存
        storageClient.decrease(order.getProductId(), order.getCount());
        //  调用account，修改账户余额
        accountClient.decrease(order.getUserId(), order.getMoney());

    }
}
